import express from 'express';
import cors from 'cors';
import helmet from 'helmet';
import morgan from 'morgan';
import dotenv from 'dotenv';
import path from 'path';
import { fileURLToPath } from 'url';

// 导入配置
import config from './config/index.js';

// 导入中间件
import { errorHandler } from './middleware/errorHandler.js';
import { rateLimiter } from './middleware/rateLimiter.js';

// 导入路由
import adminRoutes from './routes/admin.js';
import userRoutes from './routes/user.js';
import domainRoutes from './routes/domain.js';
import expertRoutes from './routes/expert.js';
import questionRoutes from './routes/question.js';
import orderRoutes from './routes/order.js';
import redeemCodeRoutes from './routes/redeemCode.js';
import serviceIntegrationRoutes from './routes/service-integration.js';
import taskRoutes from './routes/task.js';
import mobileRoutes from './routes/mobile.js';
import previewRoutes from './routes/preview.js';

// 获取当前文件目录
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

// 加载环境变量
dotenv.config();

const app = express();
const PORT = process.env.PORT || 3000;

// 基础中间件
app.use(helmet());
app.use(cors({
  origin: config.cors.origin,
  credentials: true
}));
app.use(morgan('combined'));
app.use(express.json({ limit: '10mb' }));
app.use(express.urlencoded({ extended: true, limit: '10mb' }));

// 静态文件服务
app.use('/uploads', express.static(path.join(__dirname, 'uploads')));

// 速率限制
app.use(rateLimiter);

// 手机端API路由（小程序专用）
app.use('/api/mobile', mobileRoutes);

// 管理后台API路由
app.use('/api/admin', adminRoutes);
app.use('/api/user', userRoutes);
app.use('/api/domains', domainRoutes);
app.use('/api/experts', expertRoutes);
app.use('/api/questions', questionRoutes);
app.use('/api/orders', orderRoutes);
app.use('/api/redeem-codes', redeemCodeRoutes);
app.use('/api/service-integrations', serviceIntegrationRoutes);
app.use('/api/tasks', taskRoutes);

// 预览页面路由（后端渲染）
app.use('/preview', previewRoutes);

// 健康检查
app.get('/health', (req, res) => {
  res.json({
    code: 200,
    message: 'Service is healthy',
    data: {
      status: 'OK',
      timestamp: new Date().toISOString(),
      environment: process.env.NODE_ENV || 'development'
    }
  });
});

// 404处理 - 只处理API路由
app.use('/api/*', (_req, res) => {
  res.status(404).json({
    code: 404,
    message: 'API endpoint not found',
    data: null
  });
});

// 其他路由的404处理
app.use('*', (_req, res) => {
  res.status(404).send(`
    <!DOCTYPE html>
    <html>
    <head>
      <title>页面不存在 - 彼知AI</title>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <style>
        body { font-family: Arial, sans-serif; text-align: center; padding: 50px; }
        h1 { color: #dc3545; }
        a { color: #667eea; text-decoration: none; }
        a:hover { text-decoration: underline; }
      </style>
    </head>
    <body>
      <h1>404 - 页面不存在</h1>
      <p>您访问的页面不存在</p>
      <a href="/preview">返回预览首页</a>
    </body>
    </html>
  `);
});

// 错误处理中间件
app.use(errorHandler);

// 启动服务器（跳过数据库同步）
async function startServer() {
  try {
    console.log('⚠️  跳过数据库同步，直接启动服务器...');
    
    app.listen(PORT, () => {
      console.log(`🚀 Server is running on port ${PORT}`);
      console.log(`📊 Environment: ${process.env.NODE_ENV || 'development'}`);
      console.log(`🔗 Health check: http://localhost:${PORT}/health`);
      console.log('⚠️  注意：数据库同步已跳过，请确保数据库已正确配置');
    });
  } catch (error) {
    console.error('❌ Failed to start server:', error);
    process.exit(1);
  }
}

// 优雅关闭
process.on('SIGTERM', () => {
  console.log('SIGTERM received, shutting down gracefully');
  process.exit(0);
});

process.on('SIGINT', () => {
  console.log('SIGINT received, shutting down gracefully');
  process.exit(0);
});

startServer();

export default app;
